import { StyleSheet, Text, View, ScrollView, Image, Pressable } from 'react-native';
import React, { useState, useRef, useEffect } from 'react';
import Modal from 'react-native-modal';
import { useTranslation } from 'react-i18next';
import { deviceStore, observer } from '~/store';
import { px2dp, scale } from '~/utils/px2dp';
import { ContentStatus } from '~/components';
import { yjhDevices } from '~/utils/deviceMenues';

interface Props {
    visible: boolean;
    onToggleVisible: Function;
}
export default observer((props: Props) => {
    const { t } = useTranslation();
    const { bleSearchbBindDevices }: any = deviceStore;
    const { visible, onToggleVisible } = props;
    const [isConnect, setIsConnect] = useState(false);
    const connectTimerRef: any = useRef(null);
    const [selectSn, setSelectSn] = useState('');
    const connectDevice = (item) => {
        if (isConnect) {
            Toast.show({ content: t('SelectDeviceModal.t1') });
            return;
        }
        setSelectSn(item.device_sn);
        setIsConnect(true);
        connectTimerRef.current = setTimeout(() => {
            setIsConnect(false);
            Toast.show({ content: t('ConnectDeviceModal.t1') });
            onToggleVisible && onToggleVisible();
            Toast.show({ content: t('SelectDeviceModal.t2') });
            connectTimerRef.current = null;
        }, 12000);
        if (yjhDevices.indexOf(item.device_code) !== -1) {
            deviceStore.connectBle(item, async (res) => {
                if (connectTimerRef.current) {
                    clearTimeout(connectTimerRef.current);
                    connectTimerRef.current = null;
                }
                if (res.status == 2) {
                    Toast.show({ content: t('ScanDeviceResult.t8') });
                    return;
                }
                Toast.show({ content: t('ConnectDeviceModal.t1') });
                onToggleVisible && onToggleVisible();
                setIsConnect(false);
            });
        } else {
            deviceStore.connectBleUploadData(item, async (res) => {
                if (connectTimerRef.current) {
                    clearTimeout(connectTimerRef.current);
                    connectTimerRef.current = null;
                }
                Toast.show({ content: t('ConnectDeviceModal.t1') });
                onToggleVisible && onToggleVisible();
                setIsConnect(false);
            });
        }
    };
    useEffect(() => {
        return () => {
            if (connectTimerRef.current) {
                clearTimeout(connectTimerRef.current);
            }
        };
    }, []);
    return (
        <Modal
            isVisible={visible}
            presentationStyle="overFullScreen"
            onBackdropPress={() => onToggleVisible && onToggleVisible()}
            statusBarTranslucent
            hasBackdrop>
            <View style={styles.modalContainer}>
                <Text style={styles.title}>{t('SelectDeviceModal.t3')}</Text>
                <ScrollView contentContainerStyle={styles.contentStyle} showsVerticalScrollIndicator={false}>
                    <View>
                        {bleSearchbBindDevices.length > 0 ? (
                            <View>
                                {bleSearchbBindDevices?.map((item, index) => {
                                    return (
                                        <View key={index} style={[styles.list, styles.row, styles.between]}>
                                            <View style={styles.row}>
                                                <Image source={{ uri: item.device_image }} style={styles.deviceImage} />
                                                <View style={styles.deviceInfo}>
                                                    <Text style={styles.deviceName}>
                                                        {item.prevName}.{item.device_name}
                                                    </Text>
                                                    <Text style={styles.device_sn}>{item.device_sn}</Text>
                                                    <Text style={styles.device_sn}>
                                                        {t('SelectDeviceModal.t4')}：{item.device_code}
                                                    </Text>
                                                </View>
                                            </View>
                                            <Pressable style={styles.bootom_button} onPress={() => connectDevice(item)}>
                                                <Text style={styles.bootom_buttonText}>
                                                    {isConnect && selectSn == item.device_sn
                                                        ? t('SelectDeviceModal.t5')
                                                        : t('SelectDeviceModal.t6')}
                                                </Text>
                                            </Pressable>
                                        </View>
                                    );
                                })}
                            </View>
                        ) : (
                            <ContentStatus status="empty" />
                        )}
                    </View>
                </ScrollView>
            </View>
        </Modal>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    modalContainer: {
        padding: px2dp(24),
        backgroundColor: '#fff',
        height: '50%',
        borderRadius: px2dp(26),
    },
    title: {
        textAlign: 'center',
        fontSize: scale(30),
        fontWeight: 'bold',
        color: '#000',
    },
    contentStyle: {
        flexGrow: 1,
        paddingBottom: px2dp(64),
    },
    list: {
        height: px2dp(180),
        borderBottomWidth: 1,
        borderColor: '#eee',
    },
    deviceImage: {
        width: px2dp(120),
        height: px2dp(120),
    },
    deviceInfo: {
        marginLeft: px2dp(24),
    },
    deviceName: {
        color: '#000',
        fontSize: scale(28),
    },
    device_sn: {
        color: '#a4a4a4',
        fontSize: scale(26),
        marginVertical: px2dp(6),
    },
    bootom_button: {
        backgroundColor: '#242D56',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(999),
        height: px2dp(60),
        width: px2dp(150),
    },
    bootom_buttonText: {
        color: '#fff',
        fontSize: scale(26),
        fontWeight: 'bold',
    },
});
